<template>
    <div class="vue-uploader">
        <div @click="add" class="file-box">
            <div class="file-add" v-if="!file.src" >
                <i class="el-icon-plus avatar-uploader-icon"></i>               
            </div>
            <div v-else class="file-preview">
                <img height="100%" width="100%" :src="file.src" alt="图片加载失败">
            </div>
        </div>
         <p v-if="!!label">{{label}}</p>
        <input type="file" accept="image/*" style="display:none" @change="fileChanged" ref="file">
    </div>
</template>

<script>
    export default {
        props: {
            name: {
                type: String,
                required: true
            },
            label: {
                type: String,
                default: function(){
                    return ''
                }
            },
            size: { // 上传图片大小限制 默认1M
                type: Number,
                default: function(){
                    return 1
                }
            },
            defaultSrc:{
                type:String,
                default:function(){
                    return ''
                }
            }
        },
        data() {
            return {
                file: {
                    name: null,
                    size:0,
                    file:null,
                    src:null
                },
            }
        },
        created() {
            this.file.name = this.name;
            this.file.src = this.defaultSrc;
        },
        methods: {
            add() {
                this.$refs.file.click()
            },
            fileChanged() {
                const file = this.$refs.file.files[0];
                const size = file.size;
                if(size >= this.size*1024*1024 ){
                    this.$message.error(`图片大小仅支持${this.size}M以下,请重新选择！`);
                    this.$refs.file.value = '';
                    return false;
                }
                this.file = { ...this.file, size, file};
                this.html5Reader(file,this.file);
                this.$refs.file.value = '';
            },
            // 将图片文件转成BASE64格式
            html5Reader(file, item){
                const reader = new FileReader()
                reader.onload = (e) => {
                    this.$set(item, 'src', e.target.result);
                    this.$emit('onChange',item);
                }
                reader.readAsDataURL(file) // 转化为base64
            }
        }
    }
</script>
<style>
.vue-uploader{
    text-align: center;
    width: 150px;
    padding: 10px;
    box-sizing: border-box;
}
p{
    margin: 0;
    padding: 0;
}
.file-box{
    width: 130px;
    height: 130px;
    border:1px solid #eeeeee;
    overflow: hidden;
}
.file-box>div{
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}

</style>
